<?php

require_once PHP_UI_PATH . DS . 'UIControl.php';
require_once PHP_UI_PATH . DS . 'DataSet.php';

/**
 * Description of List
 *
 * @author JeyDotC
 */
class CompositeList extends DataSetUIControl implements DataSet {

    private $children = array();

    public function setOptions(array $options) {
        parent::setOptions($options);
        $this->createChildrenFromOptions();
    }

    public function addChild(UIControl $child) {
        $this->children[] = $child;
    }

    protected function createChildrenFromOptions() {
        foreach ($this->getOptions() as $option) {
            $name = str_replace(" ", "", $option);
            $child = new Text();
            $child->setRequired(true);
            $child->setName("{$this->getName()}[$name][]");
            $child->setId($name);
            $this->addChild($child);
        }
    }

    protected function renderHead() {
        $render = "<tr>";
        foreach ($this->getOptions() as $option) {
            $render .= "<th>$option</th>";
        }

        $render .= "<th></th>";
        $render .= "</tr>";

        return $render;
    }

    protected function renderCanonicalRow() {
        $render = "";

        foreach ($this->children as /* @var $field UIControl */$field) {
            $render .= "<td>{$field->display(false)}</td>";
        }

        $render .= "<td><button class='composite-list-remove'>-</button></td>";

        return $render;
    }

    protected function renderBody() {
        $render = "<tr>{$this->renderCanonicalRow()}</tr>";
        return $render;
    }

    protected function renderFoot() {
        $span = count($this->getOptions());
        $render = "<tr><td colspan='$span'><button class='composite-list-add'>+</button></td></tr>";

        return $render;
    }

    protected function getControlRendering() {
        $render = "
        <table id='{$this->getId()}'>
            <thead>
                {$this->renderHead()}
            </thead>
            <tbody>
                {$this->renderBody()}
            </tbody>
            <tfoot>
                {$this->renderFoot()}
            </tfoot>
        </table>
        <table style='display:none' id='canonical-{$this->getId()}'>
            <tr>
                {$this->renderCanonicalRow()}
            </tr>
        </table>
        ";

        return $render;
    }

    protected function getScriptRendering() {
        return "
            $('.composite-list-add').click(function(){
                var parentId = $(this).parents('table').attr('id');
                var canonicalId = 'canonical-' + parentId;
                $('#' + parentId + ' tbody').append(
                    $('<tr>').html($('#' + canonicalId + ' tr').html())
                );
                return false;
            });
            $('.composite-list-remove').live('click', function(){
                $(this).parents('tr').remove();
                return false;
            });
            ";
    }

}

?>
